<template>
  <div class="app-container">
    <!-- 新增Tab标签切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card">
      <el-tab-pane label="后台用户" name="0"></el-tab-pane>
      <el-tab-pane label="个人用户" name="1"></el-tab-pane>
      <el-tab-pane label="企业用户" name="2"></el-tab-pane>
      <el-tab-pane label="内训用户" name="3"></el-tab-pane>
    </el-tabs>

    <el-row :gutter="20" style="margin-top: 15px;">
      <!-- 后台用户（0）显示部门树，内训用户（3）显示单位树，其他无左侧树 -->
      <template v-if="activeTab === '0' || activeTab === '3'">
        <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
          <!-- 左侧树区域 -->
          <pane size="16">
            <el-col>
              <div class="head-container">
                <el-input
                  v-model="treeSearchKey"
                  placeholder="请输入搜索关键词"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                  @input="filterTree"
                />
              </div>
              <div class="head-container">
                <!-- 后台用户：部门树（复用原有部门树逻辑） -->
                <el-tree
                  v-if="activeTab === '0'"
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  @node-click="handleNodeClick"
                />

                <!-- 内训用户：单位树（新增单位树逻辑，不修改原有方法） -->
                <el-tree
                  v-if="activeTab === '3'"
                  :data="unitsTree"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="unitTree"
                  node-key="unitId"
                  default-expand-all
                  highlight-current
                  @node-click="handleUnitNodeClick"
                />
              </div>
            </el-col>
          </pane>

          <!-- 右侧用户数据区域（复用原有列表逻辑） -->
          <pane size="84">
            <el-col>
              <div class="content-container">
                <!-- 搜索表单（复用原有） -->
                <el-form
                  :model="queryParams"
                  ref="queryForm"
                  size="small"
                  :inline="true"
                  v-show="showSearch"
                  label-width="68px"
                >
                  <el-form-item label="用户名称" prop="userName">
                    <el-input
                      v-model="queryParams.userName"
                      placeholder="请输入用户名称"
                      clearable
                      style="width: 240px"
                      @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phonenumber">
                    <el-input
                      v-model="queryParams.phonenumber"
                      placeholder="请输入手机号码"
                      clearable
                      style="width: 240px"
                      @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="状态" prop="status">
                    <el-select
                      v-model="queryParams.status"
                      placeholder="用户状态"
                      clearable
                      style="width: 240px"
                    >
                      <el-option
                        v-for="dict in dict.type.sys_normal_disable"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="创建时间">
                    <el-date-picker
                      v-model="dateRange"
                      style="width: 240px"
                      value-format="yyyy-MM-dd"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>

                <!-- 操作按钮（复用原有） -->
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-plus"
                      size="mini"
                      @click="handleAdd"
                      v-hasPermi="['system:user:add']"
                    >新增</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="success"
                      plain
                      icon="el-icon-edit"
                      size="mini"
                      :disabled="single"
                      @click="handleUpdate"
                      v-hasPermi="['system:user:edit']"
                    >修改</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="danger"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      :disabled="multiple"
                      @click="handleDelete"
                      v-hasPermi="['system:user:remove']"
                    >删除</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="info"
                      plain
                      icon="el-icon-upload2"
                      size="mini"
                      @click="handleImport"
                      v-hasPermi="['system:user:import']"
                    >导入</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="warning"
                      plain
                      icon="el-icon-download"
                      size="mini"
                      @click="handleExport"
                      v-hasPermi="['system:user:export']"
                    >导出</el-button>
                  </el-col>
                  <right-toolbar
                    :showSearch.sync="showSearch"
                    @queryTable="getList"
                    :columns="columns"
                  ></right-toolbar>
                </el-row>

                <!-- 用户表格（复用原有，仅调整列显示） -->
                <el-table
                  v-loading="loading"
                  :data="userList"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column
                    label="用户编号"
                    align="center"
                    key="userId"
                    prop="userId"
                    v-if="columns.userId.visible"
                  />
                  <el-table-column
                    label="用户名称"
                    align="center"
                    key="userName"
                    prop="userName"
                    v-if="columns.userName.visible"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="用户昵称"
                    align="center"
                    key="nickName"
                    prop="nickName"
                    v-if="columns.nickName.visible"
                    :show-overflow-tooltip="true"
                  />
                  <!-- 后台用户显示部门列，其他显示单位列 -->
                  <el-table-column
                    label="部门"
                    align="center"
                    key="deptName"
                    prop="dept.deptName"
                    v-if="columns.deptName.visible && activeTab === '0'"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="单位"
                    align="center"
                    key="unitName"
                    prop="unitName"
                    v-if="columns.unitName.visible && activeTab !== '0'"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="手机号码"
                    align="center"
                    key="phonenumber"
                    prop="phonenumber"
                    v-if="columns.phonenumber.visible"
                    width="120"
                  />
                  <el-table-column
                    label="状态"
                    align="center"
                    key="status"
                    v-if="columns.status.visible"
                  >
                    <template slot-scope="scope">
                      <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                      ></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    v-if="columns.createTime.visible"
                    width="160"
                  >
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                    width="160"
                    class-name="small-padding fixed-width"
                  >
                    <template slot-scope="scope" v-if="scope.row.userId !== 1">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:user:edit']"
                      >修改</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:user:remove']"
                      >删除</el-button>
                      <el-dropdown
                        size="mini"
                        @command="(command) => handleCommand(command, scope.row)"
                        v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
                      >
                        <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item
                            command="handleResetPwd"
                            icon="el-icon-key"
                            v-hasPermi="['system:user:resetPwd']"
                          >重置密码</el-dropdown-item>
                          <el-dropdown-item
                            command="handleAuthRole"
                            icon="el-icon-circle-check"
                            v-hasPermi="['system:user:edit']"
                          >分配角色</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页（复用原有） -->
                <pagination
                  v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
                />
              </div>
            </el-col>
          </pane>
        </splitpanes>
      </template>

      <!-- 个人用户（1）和企业用户（2）无左侧树 -->
      <template v-else>
        <div class="full-width-content">
          <!-- 内容与右侧区域一致，复用原有逻辑 -->
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="用户状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['system:user:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:user:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['system:user:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['system:user:import']"
              >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['system:user:export']"
              >导出</el-button>
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
              :columns="columns"
            ></right-toolbar>
          </el-row>

          <el-table
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="用户编号"
              align="center"
              key="userId"
              prop="userId"
              v-if="columns.userId.visible"
            />
            <el-table-column
              label="用户名称"
              align="center"
              key="userName"
              prop="userName"
              v-if="columns.userName.visible"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="用户昵称"
              align="center"
              key="nickName"
              prop="nickName"
              v-if="columns.nickName.visible"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="单位"
              align="center"
              key="unitName"
              prop="unitName"
              v-if="columns.unitName.visible"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机号码"
              align="center"
              key="phonenumber"
              prop="phonenumber"
              v-if="columns.phonenumber.visible"
              width="120"
            />
            <el-table-column
              label="状态"
              align="center"
              key="status"
              v-if="columns.status.visible"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              v-if="columns.createTime.visible"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope" v-if="scope.row.userId !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:user:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
                >删除</el-button>
                <el-dropdown
                  size="mini"
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
                >
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      command="handleResetPwd"
                      icon="el-icon-key"
                      v-hasPermi="['system:user:resetPwd']"
                    >重置密码</el-dropdown-item>
                    <el-dropdown-item
                      command="handleAuthRole"
                      icon="el-icon-circle-check"
                      v-hasPermi="['system:user:edit']"
                    >分配角色</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </template>
    </el-row>

    <!-- 添加或修改用户配置对话框（复用原有，仅调整字段显示） -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 后台用户显示部门选择，内训/个人/企业显示单位选择 -->
            <el-form-item label="归属部门" prop="deptId" v-if="activeTab === '0'">
              <treeselect
                v-model="form.deptId"
                :options="enabledDeptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
            <el-form-item label="学历" prop="unitId">
              <el-select v-model="form.qualification" placeholder="请选择学历">
                <el-option
                  v-for="dict in dict.type.pxzx_xl"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="所属单位" prop="unitId" v-if="activeTab === '3'">
              <treeselect
                v-model="form.unitId"
                :options="unitsTree"
                :show-count="true"
                placeholder="请选择所属单位"
              />
            </el-form-item>
            <el-form-item label="所属单位" prop="unitId" v-if="activeTab === '1' || activeTab === '2'">
              <el-select v-model="form.unitId" placeholder="请选择单位">
                <el-option
                  v-for="dict in unitsList"
                  :key="dict.unitId"
                  :label="dict.unitName"
                  :value="dict.unitId"
                ></el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
        </el-row>
        <!-- 以下表单内容完全复用原有，未做修改 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="证件类型" prop="documentType">
              <el-select v-model="form.documentType" placeholder="请选择证件类型">
                <el-option
                  v-for="dict in dict.type.pxzx_zjlx"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入证件号" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类别" prop="exampleOne">
              <el-radio-group v-model="form.exampleOne" :disabled="true">
                <el-radio label="0">后台用户</el-radio>
                <el-radio label="1">个人学员</el-radio>
                <el-radio label="2">企业学员</el-radio>
                <el-radio label="3">内训</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择民族">
                <el-option
                  v-for="dict in dict.type.pub_mz"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitId" v-if="activeTab !== '0'">
              <el-select v-model="form.unitId" placeholder="请选择单位">
                <el-option
                  v-for="dict in unitsList"
                  :key="dict.unitId"
                  :label="dict.unitName"
                  :value="dict.unitId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="positionRank">
              <el-input v-model="form.positionRank" placeholder="请输入用户职级" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="!form.userId" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="!form.userId" label="用户密码" prop="password">
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择岗位">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框（复用原有，仅添加用户类型参数） -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&exampleOne=' + activeTab"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 完全复用原有导入，未做任何修改
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect
} from "@/api/system/user"
import { getToken } from "@/utils/auth"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import RightToolbar from "@/components/RightToolbar"
import Pagination from "@/components/Pagination"
import { listUnits } from "@/api/training/units"

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex','pxzx_zjlx','pub_mz','rylx','units',"pxzx_xl"],
  components: { Treeselect, Splitpanes, Pane, RightToolbar, Pagination },
  data() {
    return {
      // 新增Tab相关状态
      activeTab: '0', // 默认显示后台用户
      treeSearchKey: '', // 树搜索关键词
      unitsTree: [], // 单位树形结构（新增，不影响原有数据）

      // 以下数据完全复用原有，未做任何修改
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      userList: null,
      title: "",
      deptOptions: undefined,
      enabledDeptOptions: undefined,
      open: false,
      deptName: undefined, // 原部门搜索，在Tab=0时仍可用
      initPassword: undefined,
      dateRange: [],
      postOptions: [],
      unitsList:[],
      roleOptions: [],
      form: {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        documentType: null,
        idNumber: null,
        exampleOne: null,
        nation: null,
        unitId: null // 新增单位ID字段，不影响原有
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        unitId: undefined, // 新增单位查询参数，不影响原有
        exampleOne: '0' // 新增用户类型查询参数，不影响原有
      },
      columns: {
        userId: { label: '用户编号', visible: true },
        userName: { label: '用户名称', visible: true },
        nickName: { label: '用户昵称', visible: true },
        deptName: { label: '部门', visible: true },
        unitName: { label: '单位', visible: true }, // 新增单位列，不影响原有
        phonenumber: { label: '手机号码', visible: true },
        status: { label: '状态', visible: true },
        createTime: { label: '创建时间', visible: true }
      },
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        documentType: [
          { required: true, message: "证件类型不能为空", trigger: "change" }
        ],
        idNumber: [
          { required: true, message: "证件号不能为空", trigger: "blur" },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        exampleOne: [
          { required: true, message: "用户类别不能为空", trigger: "change" }
        ],
        nation: [
          { required: true, message: "民族不能为空", trigger: "change" }
        ]
      }
    }
  },
  watch: {
    // 保留原有部门搜索监听，仅在Tab=0时生效
    deptName(val) {
      if (this.activeTab === '0') {
        this.$refs.tree.filter(val)
      }
    },
    // 新增树搜索监听（不影响原有）
    treeSearchKey(val) {
      this.filterTree()
    }
  },
  created() {
    // 保留原有初始化逻辑，新增单位树初始化
    this.getList()
    this.getUnitList()
    this.getDeptTree()
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg
    })
  },
  methods: {
    // 新增Tab切换处理（不影响原有方法）
    handleTabClick(tab) {
      this.activeTab = tab.name
      // 重置查询参数，按用户类型筛选
      this.queryParams = {
        ...this.queryParams,
        pageNum: 1,
        deptId: undefined,
        unitId: undefined,
        exampleOne: this.activeTab
      }
      this.dateRange = []
      this.ids = []
      this.single = true
      this.multiple = true

      // 按Tab加载对应树
      if (this.activeTab === '0') {
        this.getDeptTree() // 复用原有部门树方法
      } else if (this.activeTab === '3') {
        this.getUnitsTree() // 新增单位树方法，不影响原有
      }

      this.getList() // 复用原有列表方法
    },

    // 新增单位树构建（不影响原有方法）
    async getUnitsTree() {
      const res = await listUnits({}); // 复用原有单位列表接口
      this.unitsTree = this.buildUnitsTree(res.rows, 0)
    },

    // 新增单位树构建逻辑（不影响原有方法）
    buildUnitsTree(data, parentId) {
      const tree = []
      data.forEach(item => {
        if (item.parentId === parentId) {
          const children = this.buildUnitsTree(data, item.unitId)
          if (children.length > 0) {
            item.children = children
          }
          item.label = item.unitName // 适配树组件label字段
          tree.push(item)
        }
      })
      return tree
    },

    // 新增树过滤（不影响原有方法）
    filterTree() {
      if (this.activeTab === '0' && this.$refs.tree) {
        this.$refs.tree.filter(this.treeSearchKey)
      } else if (this.activeTab === '3' && this.$refs.unitTree) {
        this.$refs.unitTree.filter(this.treeSearchKey)
      }
    },

    // 新增单位树节点点击（不影响原有方法）
    handleUnitNodeClick(data) {
      this.queryParams.unitId = data.unitId
      this.queryParams.deptId = undefined
      this.handleQuery() // 复用原有查询方法
    },

    // 以下方法完全复用原有，未做任何修改
    async getUnitList(){
      const res =await listUnits({});
      this.unitsList=res.rows
    },
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm(`确认要"${text}""${row.userName}"用户吗？`).then(() => {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(`${text}成功`)
      }).catch(() => {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        documentType: null,
        idNumber: null,
        exampleOne: this.activeTab, // 仅修改默认值为当前Tab，不改变方法逻辑
        nation: null,
        unitId: null
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams.deptId = undefined
      this.queryParams.unitId = undefined // 新增重置单位ID，不影响原有逻辑
      if (this.activeTab === '0' && this.$refs.tree) {
        this.$refs.tree.setCurrentKey(null)
      } else if (this.activeTab === '3' && this.$refs.unitTree) {
        this.$refs.unitTree.setCurrentKey(null)
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row)
          break
        case "handleAuthRole":
          this.handleAuthRole(row)
          break
        default:
          break
      }
    },
    handleAdd() {
      this.reset()
      getUser().then(response => {
        this.postOptions = response.posts
        this.roleOptions = response.roles
        this.open = true
        this.title = "添加用户"
        this.form.password = this.initPassword
        this.form.exampleOne = this.activeTab // 仅设置用户类型为当前Tab，不改变方法逻辑
      })
    },
    handleUpdate(row) {
      this.reset()
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = { ...response.data }
        this.postOptions = response.posts
        this.roleOptions = response.roles
        this.$set(this.form, "postIds", response.postIds)
        this.$set(this.form, "roleIds", response.roleIds)
        this.form.documentType = response.data.documentType || null
        this.form.idNumber = response.data.idNumber || null
        this.form.exampleOne = response.data.exampleOne || null
        this.form.nation = response.data.nation || null
        this.form.unitId = response.data.unitId || null // 新增单位ID回显，不影响原有逻辑
        this.open = true
        this.title = "修改用户"
        this.form.password = ""
      })
    },
    handleResetPwd(row) {
      this.$prompt(`请输入"${row.userName}"的新密码`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(() => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value)
          })
        }).catch(() => {})
    },
    handleAuthRole(row) {
      const userId = row.userId
      this.$router.push(`/system/user-auth/role/${userId}`)
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId) {
            updateUser(this.form).then(() => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(() => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm(`是否确认删除用户编号为"${userIds}"的数据项？`).then(() => {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams,
        exampleOne: this.activeTab // 仅添加用户类型参数，不改变方法逻辑
      }, `user_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.upload.title = "用户导入"
      this.upload.open = true
    },
    importTemplate() {
      this.download('system/user/importTemplate', {
        exampleOne: this.activeTab // 仅添加用户类型参数，不改变方法逻辑
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(`<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`, "导入结果", {
        dangerouslyUseHTMLString: true
      })
      this.getList()
    },
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
/* 保留原有样式，新增必要样式不影响原有 */
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.head-container {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  height: calc(100% - 20px);
}
.full-width-content {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
}
.content-container {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  height: 100%;
}
::v-deep .el-tabs__content {
  margin-top: 15px;
}
::v-deep .splitpanes__pane {
  overflow: auto;
}
</style>
